<template>
  <div ref="chartContainer" class="chart-container"></div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { useAnalysisStore } from '@/stores/analysisStore'

const props = defineProps({
  city: {
    type: String,
    required: true
  }
})

const analysisStore = useAnalysisStore()
const chartContainer = ref(null)
let chart = null
const loading = ref(false)

const initChart = () => {
  if (!chartContainer.value) return
  
  chart = echarts.init(chartContainer.value)
  chart.showLoading()
}

const loadData = async () => {
  if (!props.city) return
  
  loading.value = true
  try {
    const data = await analysisStore.fetchDecorationDistribution(props.city)
    renderChart(data)
  } catch (error) {
    console.error('加载装修分布数据失败:', error)
  } finally {
    loading.value = false
    if (chart) {
      chart.hideLoading()
    }
  }
}

const renderChart = (data) => {
  if (!chart) return
  
  const option = {
    title: {
      text: `${props.city}装修情况分布`,
      left: 'center',
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: data.decorations,
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '房源数量'
      }
    ],
    series: [
      {
        name: '房源数量',
        type: 'bar',
        barWidth: '60%',
        data: data.decorations.map((decoration, index) => {
          const colors = {
            '精装修': '#91cc75',
            '简装修': '#fac858',
            '毛坯': '#ee6666',
            '豪华装修': '#5470c6',
            '中等装修': '#73c0de'
          }
          
          return {
            value: data.counts[index],
            name: decoration,
            itemStyle: {
              color: colors[decoration] || '#3ba272'
            }
          }
        })
      }
    ]
  }
  
  chart.setOption(option)
}

const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}

watch(() => props.city, () => {
  loadData()
})

onMounted(() => {
  initChart()
  loadData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style> 